package com.javiercp.ayudaapp.contacts;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;

public class ContactAccessorSDK5 extends ContactAccessor {

	@Override
	public Intent getPickContactIntent() {
        //return new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
		return new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
	}

	@Override
	public ContactInfo loadContact(ContentResolver contentResolver, Uri contactUri) {
        ContactInfo contactInfo = new ContactInfo();

        Cursor cursor = contentResolver.query(contactUri, 
        		new String[]{Contacts._ID, 
        		Contacts.DISPLAY_NAME}, 
        		null, null, null);
        try {
            if (cursor.moveToFirst()) {
                contactInfo.setContactID(cursor.getLong(0));
                contactInfo.setDisplayName(cursor.getString(1));
                contactInfo.setContactUri(contactUri);
            }
        } finally {
            cursor.close();
        }

        return contactInfo;
	}

	@Override
	public ArrayList<ContactPhone> getContactPhones(ContentResolver contentResolver, ContactInfo contactInfo) {
		ArrayList<ContactPhone> retValue = new ArrayList<ContactPhone>();
		
		Cursor cursor = contentResolver.query(Phone.CONTENT_URI,
                new String[]{Phone._ID, Phone.NUMBER, Phone.TYPE},
                Phone.CONTACT_ID + "=" + contactInfo.getContactID(), 
                null, 
                Phone.IS_SUPER_PRIMARY + " DESC");
        try {
        	while (cursor.moveToNext()) {        		     		
        		retValue.add(new ContactPhone(cursor.getString(cursor.getColumnIndex(Phone.NUMBER)), 
        				cursor.getString(cursor.getColumnIndex(Phone.TYPE))));
        	}
        } finally {
            cursor.close();
        }
        
        return retValue;		
	}
	
	@Override
	public ArrayList<ContactEmail> getContactEmails(ContentResolver contentResolver, ContactInfo contactInfo) {
		ArrayList<ContactEmail> retValue = new ArrayList<ContactEmail>();

        Cursor cursor = contentResolver.query(Email.CONTENT_URI,
                new String[]{Email._ID, Email.DATA, Email.TYPE},
                Email.CONTACT_ID + "=" + contactInfo.getContactID(), 
                null, null);
        try {
        	while (cursor.moveToNext()) {        		     		
        		retValue.add(new ContactEmail(cursor.getString(cursor.getColumnIndex(Email.DATA)), 
        				cursor.getString(cursor.getColumnIndex(Email.TYPE))));
        	}
        } finally {
            cursor.close();
        }
        
        return retValue;
	}
	
}
